package com.bringway.p2p.controller;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.bringway.framework.controller.JsonController;
import com.bringway.framework.excel.ExcelOperUtil;
import com.bringway.framework.excel.ExcelSheet;
import com.bringway.framework.exception.ServiceException;
import com.bringway.framework.util.DateUtils;
import com.bringway.framework.util.RequestUtils;
import com.bringway.global.domain.SysUserDetails;
import com.bringway.p2p.service.CjService;


/**  
 * @类名 CjController  
 * @功能 TODO  抽奖人员信息管理
 * @作者 js 
 * @日期 2016年11月30日 下午4:41:57  
 *    
 */
@Controller
@RequestMapping("/cj")
public class CjController extends JsonController {

	@Autowired
	private CjService cjService;
	private Logger logger=Logger.getLogger(CjController.class);
	
	private static final long UPLOAD_FILE_SIZE = 30971520;//允许上传图片大小
	private static String ROOT_PATH="e:/cj/";//图片存储文件夹
	private static String DEFAULT_PIC_PATH="00000000.jpg";//文件不存在显示的图片

	/**
	 * @作者 js  
	 * @方法名 queryCjListAll  
	 * @功能 TODO 抽奖人员信息 查询
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryCjListAll")
	public ModelAndView queryCjListAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		Integer page = RequestUtils.getIntParameter(request, "page");// 新版本,传参
		Integer start = RequestUtils.getIntParameter(request, "start");
		Integer limit = RequestUtils.getIntParameter(request, "limit");
		if (null != page) {// 新版本,传参
			start = (page - 1) * limit;
		}
		String gyh = RequestUtils.getStringParameter(request, "gyh");
		String xm = RequestUtils.getStringParameter(request, "xm");
		String iszj = RequestUtils.getStringParameter(request, "iszj");
		params.put("start", start);
		params.put("limit", limit);
		params.put("gyh", gyh);
		params.put("xm", xm);
		params.put("iszj", iszj);
		List<Map<String, Object>> list = cjService.queryCjListAll(params);
		for (Map<String, Object> map : list) {
			File file=new File(ROOT_PATH+MapUtils.getString(map, "PIC_PATH"));
			if (file.exists()) {
				map.put("ISBE", true);
			}else {
				map.put("ISBE", false);
			}
		}
		int count = cjService.getCjListCount(params);
		result.put("data", list);
		result.put("total", count);
		if (null != page) {// 新版本,传参
			int totalPage = count % limit == 0 ? count / limit : count / limit + 1;
			result.put("totalPage", totalPage);
		}
		serialize(request, response, result);
		return null;
	}
	/**
	 * @作者 js  
	 * @方法名 upload  
	 * @功能 TODO 插入抽奖人员信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		String gyh=RequestUtils.getStringParameter(request, "gyh").trim();
		if (cjService.isBe(gyh)) {
			result.put("success", true);
			result.put("isSuc", false);
			result.put("msg", "员工号已存在");
			serialize(request, response, result);
			return;
		}
		String xm=RequestUtils.getStringParameter(request, "xm");
		String rygw=RequestUtils.getStringParameter(request, "rygw");
		String xb=RequestUtils.getStringParameter(request, "xb");
		MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) mrequest.getFile("file");
		if (UPLOAD_FILE_SIZE < new Long(file.getSize()).longValue()) {
			throw new ServiceException("只能上传30M以内的附件！");
		}
		String fileName=file.getOriginalFilename();
		String fileNames[] = new String[2];
		fileNames[0]=gyh+"-"+xm;
		fileNames[1]=StringUtils.substringAfterLast(fileName, ".");
		fileName=StringUtils.join(fileNames, '.');
		String contextType=file.getContentType();
		String picPath=ROOT_PATH;
		File file2=new File(picPath);
		if (!file2.exists()) {
			file2.mkdirs();
		}
		DataOutputStream out = new DataOutputStream(new FileOutputStream(picPath+fileName));//输出流
		InputStream is = null;// 输入流
		try {
			is = file.getInputStream();
			byte[] b = new byte[is.available()];
			is.read(b);
			out.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
		JSONObject params = new JSONObject();
		params.put("gyh", gyh);
		params.put("xm", xm);
		params.put("rygw", rygw);
		params.put("xb", xb);
		params.put("contentType", contextType);
		params.put("picPath", fileName);
		boolean isSuc=cjService.insertCj(params);
		if (isSuc) {
			result.put("isSuc", true);
			result.put("msg", "保存成功");
		}else {
			result.put("isSuc", false);
			result.put("msg", "保存失败");
		}
		result.put("success", true);
		serialize(request, response, result);
	}
	/**
	 * @作者 js  
	 * @方法名 downloadFile  
	 * @功能 TODO 输出图片
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloadFile")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String picPath = RequestUtils.getStringParameter(request, "picPath");
		picPath=new String(picPath.getBytes("iso-8859-1"), "utf-8");
		File file=new File(ROOT_PATH+picPath);
		if (!file.exists()) {
			picPath=DEFAULT_PIC_PATH;
		}
		OutputStream  out =response.getOutputStream();
		InputStream is = new FileInputStream(new File(ROOT_PATH+picPath));
		try {
			byte[] b = new byte[is.available()];
			is.read(b);
			out.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
	/**
	 * @作者 js  
	 * @方法名 updateFile  
	 * @功能 TODO 修改抽奖人员信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateFile", method = RequestMethod.POST)
	public void updateFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		String gyh=RequestUtils.getStringParameter(request, "gyh");
		String xm=RequestUtils.getStringParameter(request, "xm");
		String rygw=RequestUtils.getStringParameter(request, "rygw");
		String xb=RequestUtils.getStringParameter(request, "xb");
		String picPath=RequestUtils.getStringParameter(request, "picPath");
		JSONObject params = new JSONObject();
		params.put("gyh", gyh);
		params.put("xm", xm);
		params.put("rygw", rygw);
		params.put("xb", xb);
		MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) mrequest.getFile("file");
		if (null!=file&&!file.isEmpty()) {
		if (UPLOAD_FILE_SIZE < new Long(file.getSize()).longValue()) {
			throw new ServiceException("只能上传30M以内的附件！");
		}
		String fileName=file.getOriginalFilename();
		String fileNames[] = new String[2];
		fileNames[0]=gyh+"-"+xm;
		fileNames[1]=StringUtils.substringAfterLast(fileName, ".");
		fileName=StringUtils.join(fileNames, '.');
		String contextType=file.getContentType();
		params.put("contentType", contextType);
		picPath=ROOT_PATH;
		params.put("picPath", fileName);
		File file2=new File(picPath);
		if (!file2.exists()) {
			file2.mkdirs();
		}
		DataOutputStream out = new DataOutputStream(new FileOutputStream(picPath+fileName));// 存放文件的绝对路径
		InputStream is = null;// 附件输入流
		try {
			is = file.getInputStream();
			byte[] b = new byte[is.available()];
			is.read(b);
			out.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
		}else {
			//修改数据库中图片路径
			String fileNames[] = new String[2];
			fileNames[0]=gyh+"-"+xm;
			fileNames[1]=StringUtils.substringAfterLast(picPath, ".");
			String picPath_x=StringUtils.join(fileNames, '.');
			params.put("picPath", picPath_x);
			//修改文件名
			File file2=new File(ROOT_PATH+picPath);
			if (file2.exists()) {
				file2.renameTo(new File(ROOT_PATH+picPath_x));
			}
		}
		
		boolean isSuc=cjService.updateCj(params);
		if (isSuc) {
			result.put("isSuc", true);
			result.put("msg", "修改成功");
		}else {
			result.put("isSuc", false);
			result.put("msg", "修改失败");
		}
		result.put("success", true);
		serialize(request, response, result);
	}
	@RequestMapping("/deleteCj")
	public void deleteCj(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		String id=RequestUtils.getStringParameter(request, "id");
		String picPath=RequestUtils.getStringParameter(request, "picPath");
		//picPath=new String(picPath.getBytes("iso-8859-1"), "utf-8");
		params.put("id", id);
		File file=new File(ROOT_PATH+picPath);
		if (file.exists()) {
			file.delete();//删除文件
		}
		boolean isSuc=cjService.deleteCj(params);
		if (isSuc) {
			result.put("isSuc", true);
			result.put("msg", "删除成功");
		}else {
			result.put("isSuc", false);
			result.put("msg", "删除失败");
		}
		result.put("success", true);
		serialize(request, response, result);
	}
	/**
	 * @作者 js  
	 * @方法名 exportCjZjExcelMethod  
	 * @功能 TODO 中奖信息下载
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("exportCjZjExcelMethod")
	public ModelAndView exportCjZjExcelMethod(HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject params = new JSONObject();
		params.put("iszj", "1");//是否中奖,中奖
		params.put("isdown", true);//是否是下载功能,是
		// 查询数据
		List list = cjService.queryCjListAll(params);
		List<String[]> dataList = com.bringway.p2p.constant.ExcelHeadConstant.getCjZjExportSearchResultData(list);
		
		// 导出数据到Excel文件
		List<ExcelSheet> sheetList = new ArrayList<ExcelSheet>();
		ExcelSheet sheet = new ExcelSheet();
		sheet.setBodyList(dataList);
		sheet.setSheetName("中奖信息");
		sheetList.add(sheet);
		OutputStream os = response.getOutputStream();
		String fileName = DateUtils.getCurrentDataStr() + "年会中奖信息.xls";
		super.setDownLoadResponseHeader(request, response, fileName);
		response.setContentType("application/vnd.ms-excel");
		
		// 导出EXCEL
		ExcelOperUtil.writeExcel(sheetList, os);
		return null;
	}
	/**
	 * @作者 js  
	 * @方法名 queryZnqCjList  
	 * @功能 TODO 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryZnqCjList")
	public ModelAndView queryZnqCjList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		Integer page = RequestUtils.getIntParameter(request, "page");// 新版本,传参
		Integer start = RequestUtils.getIntParameter(request, "start");
		Integer limit = RequestUtils.getIntParameter(request, "limit");
		if (null != page) {// 新版本,传参
			start = (page - 1) * limit;
		}
		String startDate = RequestUtils.getStringParameter(request, "startDate");
		String endDate = RequestUtils.getStringParameter(request, "endDate");
		String startDateLq = RequestUtils.getStringParameter(request, "startDateLq");
		String endDateLq = RequestUtils.getStringParameter(request, "endDateLq");
		String username = RequestUtils.getStringParameter(request, "username");
		String xm = RequestUtils.getStringParameter(request, "xm");
		String sjhm = RequestUtils.getStringParameter(request, "sjhm");
		String cjType = RequestUtils.getStringParameter(request, "cjType");
		String lqState = RequestUtils.getStringParameter(request, "lqState");
		params.put("start", start);
		params.put("limit", limit);
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		params.put("startDateLq", startDateLq);
		params.put("endDateLq", endDateLq);
		params.put("username", username);
		params.put("xm", xm);
		params.put("sjhm", sjhm);
		params.put("cjType", cjType);
		params.put("lqState", lqState);
		List<Map<String, Object>> list = cjService.listZnqCj(params);
		int count = cjService.getZnqCjCount(params);
		result.put("data", list);
		result.put("total", count);
		if (null != page) {// 新版本,传参
			int totalPage = count % limit == 0 ? count / limit : count / limit + 1;
			result.put("totalPage", totalPage);
		}
		serialize(request, response, result);
		return null;
	}
	/**
	 * @作者 js  
	 * @方法名 updateZnqCj  
	 * @功能 TODO 奖品签收
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/updateZnqCj")
	public void updateZnqCj(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysUserDetails sysUserDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		JSONObject result = new JSONObject();
		JSONObject params = new JSONObject();
		String id=RequestUtils.getStringParameter(request, "id");
		String ffCom=RequestUtils.getStringParameter(request, "ffCom");
		params.put("id", id);
		params.put("ffGyh", sysUserDetails.getGyh());
		params.put("ffCom", ffCom);
		boolean isSuc=cjService.updateZnqCj(params);
		if (isSuc) {
			result.put("isSuc", true);
			result.put("msg", "签收成功");
		}else {
			result.put("isSuc", false);
			result.put("msg", "签收失败");
		}
		result.put("success", true);
		serialize(request, response, result);
	}
	/**
	 * @作者 js  
	 * @方法名 exportZnqCjExcelMethod  
	 * @功能 TODO 中奖信息下载
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("exportZnqCjExcelMethod")
	public ModelAndView exportZnqCjExcelMethod(HttpServletRequest request, HttpServletResponse response) throws Exception{
		JSONObject params = new JSONObject();
		String startDate = RequestUtils.getStringParameter(request, "startDate");
		String endDate = RequestUtils.getStringParameter(request, "endDate");
		String startDateLq = RequestUtils.getStringParameter(request, "startDateLq");
		String endDateLq = RequestUtils.getStringParameter(request, "endDateLq");
		String username = RequestUtils.getStringParameter(request, "username");
		String xm = RequestUtils.getStringParameter(request, "xm");
		String sjhm = RequestUtils.getStringParameter(request, "sjhm");
		String cjType = RequestUtils.getStringParameter(request, "cjType");
		String lqState = RequestUtils.getStringParameter(request, "lqState");
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		params.put("startDateLq", startDateLq);
		params.put("endDateLq", endDateLq);
		params.put("username", username);
		params.put("xm", URLDecoder.decode(xm));
		params.put("sjhm", sjhm);
		params.put("cjType", cjType);
		params.put("lqState", lqState);
		List<Map<String, Object>> list = cjService.listZnqCj(params);
		// 查询数据
		List<String[]> dataList = com.bringway.p2p.constant.ExcelHeadConstant.getZnqCjExportSearchResultData(list);
		
		// 导出数据到Excel文件
		List<ExcelSheet> sheetList = new ArrayList<ExcelSheet>();
		ExcelSheet sheet = new ExcelSheet();
		sheet.setBodyList(dataList);
		sheet.setSheetName("中奖信息");
		sheetList.add(sheet);
		OutputStream os = response.getOutputStream();
		String fileName = DateUtils.getCurrentDataStr() + "周年庆抽奖中奖信息.xls";
		super.setDownLoadResponseHeader(request, response, fileName);
		response.setContentType("application/vnd.ms-excel");
		
		// 导出EXCEL
		ExcelOperUtil.writeExcel(sheetList, os);
		return null;
	}

}
